package com.liesp.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

import net.news.entity.NewsPeople;

public class RoleFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 2L;
	// 1,doFilter方法的第一个参数为ServletRequest对象。
	// 此对象给过滤器提供了对进入的信息（包括表单数据、cookie和HTTP请求头）的完全访问。
	// 第二个参数为ServletResponse，通常在简单的过滤器中忽略此参数。
	// 最后一个参数为FilterChain，此参数用来调用servlet或JSP页。
	private FilterConfig filterConfig;
	private FilterChain chain;
	private HttpServletRequest request;
	private HttpServletResponse response;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		this.chain = chain;
		this.request = (HttpServletRequest) request;
		RequestDispatcher dispatcher = request.getRequestDispatcher("/pages/news/login_user/index.jsp");
		// 如果处理HTTP请求，并且需要访问诸如getHeader或getCookies等在ServletRequest中无法得到的方法，
		// 就要把此request对象构造成HttpServletRequest
		this.response = ((HttpServletResponse) response);
		// 获取当前页面文件名此处url为：/Gzlkh/login.jsp
		String url = ((HttpServletRequest) request).getRequestURI();
		System.out.println(url);
		// 此处截取的url为：login.jsp
		url = url.substring(url.indexOf("/", 1) + 1, url.length());
		System.out.println(url);
		try {
			HttpSession session = ((HttpServletRequest) request).getSession();
			// 获取网站访问根目录
			String accessPath = ((HttpServletRequest) request).getContextPath();
			// 获取用户登录验证信息
			NewsPeople newsPeople = (NewsPeople) session
					.getAttribute(ConstantUtils.USER_LOGIN_SESSIOIN);
			if (url.length() > 0 && noFileUrl(url, this.request)) {
				// 不需要判断权限的请求如登录页面，则跳过
				chain.doFilter(request, response);// 继续执行请求
			} else if (newsPeople == null||url.indexOf(".jsp")>0) {
				dispatcher.forward(request, response);
				((HttpServletResponse) response).setHeader("Cache-Control",
						"no-store");
				((HttpServletResponse) response).setDateHeader("Expires", 0);
				((HttpServletResponse) response)
						.setHeader("Pragma", "no-cache");
			} else {
				verifyUrl(url, newsPeople);
			}// 判断当前user是否拥有访问此url的权限
		} catch (Exception sx) {
			sx.printStackTrace();
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	/**
	 * 判断当前user是否拥有访问此url的权限
	 * 
	 * @param url
	 *            当前请求的url
	 * @param st
	 *            当前登录用户信息
	 * @throws IOException
	 * @throws ServletException
	 */
	private void verifyUrl(String url, NewsPeople newsPeople)
			throws IOException, ServletException {
		// 获取user拥有的所有资源串，此处全部提取出来，以方便以后项目扩展
		// 更好的方式是把此处的权限页面存储在数据库中，与角色建立关系，以后可以直接根据用户角色从
		// 数据库中取出
		String sturl = null;
		// 拥有权限页1的jsp页面
		String url1 = "/news_view/editview/,/news_view/editnews/,/news_view/delete_news/";
		// // 拥有权限页2的jsp页面
		String url2 = "/news_view/news_list/,/news_view/newsinfo/,/news_type/";
		// 公共
		String url7 = "/login_user/index,/first_page/backstage/,/news_view/addnews/";
		sturl = url7;
		// 以下判断用户是否有进入该页面的权限，有则加入
		if (1 == (newsPeople.getPopleType())) {
			sturl = sturl + "," + url1 + "," + url2;
		}
		if (2 == (newsPeople.getPopleType())) {
			sturl = sturl + "," + url2;
		}
		if (sturl.indexOf(url) >= 0||0==newsPeople.getPopleType()) {
			// 判断用户权限页面包含请求url里面的页面
			chain.doFilter(request, response);
		}
		else {
			// 用户无权限跳转提示
				response.setContentType("text/html;charset=UTF-8");
				response
						.getWriter()
						.println(
								"<script type='text/javascript'>alert('您没有权限!');history.go(-1);</script>");
		}
	}

	/**
	 * 特殊页面判断 是否需要判断权限,如客户端浏览、登录页面则不需要判断权限
	 */
	protected boolean noFileUrl(String url, HttpServletRequest request) {
		// 不需要权限验证的页面动作等
		String exclude = "/cmunews3084/login_user/login,/pages/news/kindeditor/upload_json.jsp";
		// 判断请求页面是否是特殊页面
		if (exclude.indexOf(url) >= 0) {
			return true;
		}
		return false;
	}
}
